package com.harmony.rabbitmq.dlq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列的消费者！！！
 * 被声明成死信交换机了，这个是配置死信队列的消费者
 */
public class SimpleConsumer {

    private static final String HOST_NAME="nas-map.u1600292.nyat.app";
    private static final int HOST_PORT=59620;

    // 死信交换机
    private static final String EXCHANGE_NAME="testdlq.exchange";
    // 死信队列
    private static final String QUEUE_NAME="testdlq";
    public static final String USER_NAME="guest";
    public static final String PASSWORD="guest";
    public static final String VIRTUAL_HOST="/";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_NAME);
        factory.setPort(HOST_PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true, false, null);
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");

        //回调函数，处理接收到的消息
        Consumer myconsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                System.out.println(properties.getHeaders());

//                System.out.println("========================");
//                String routingKey = envelope.getRoutingKey();
//                System.out.println("routingKey >"+routingKey);
//                String contentType = properties.getContentType();
//                System.out.println("contentType >"+contentType);
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag >"+deliveryTag);
                System.out.println("content:"+new String(body,"UTF-8"));
                // (process the message components here ...)
                channel.basicAck(deliveryTag, false);
            }
        };
        //从test1队列接收消息
        channel.basicConsume(QUEUE_NAME, false,myconsumer);
    }
}
